//
//  CacheFileManager.m
//  CedarFinancePH
//
//  Created by lshenrong on 2018/3/21.
//  Copyright © 2018年 cedarhd. All rights reserved.
//

#import "CacheFileManager.h"
#import <WebKit/WebKit.h>
#import "SDImageCache.h"
#import "YYCache.h"

@interface CacheFileManager()


@end


@implementation CacheFileManager


+ (instancetype) shareInstance{
    static dispatch_once_t onceToken ;
    static CacheFileManager *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init] ;
    }) ;
    return instance ;
}


- (void)deleteWebCache{
    if (@available(iOS 9.0, *)) {
        NSArray * types = @[WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeOfflineWebApplicationCache,
                            WKWebsiteDataTypeCookies,WKWebsiteDataTypeCookies,WKWebsiteDataTypeSessionStorage,
                            WKWebsiteDataTypeLocalStorage,WKWebsiteDataTypeLocalStorage,WKWebsiteDataTypeWebSQLDatabases,
                            WKWebsiteDataTypeIndexedDBDatabases];
        NSSet *websiteDataTypes = [NSSet setWithArray:types];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            
        }];
    }else{
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        CDebugLog(@"Cookies %@", cookiesFolderPath);
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
}


//单个文件的大小
- (long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager * manager = [ NSFileManager defaultManager ];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
    }
    return 0 ;
}

//遍历文件夹大小，返回多少M
- (long long) folderSizeAtPath:(NSString *) folderPath{
    NSFileManager * manager = [ NSFileManager defaultManager ];
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
    }
    return folderSize;
}

//主要是Library/cache路径
- (void)clearCacheAtPath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    for (NSString *p in files) {
        NSError *error;
        NSString *Path = [path stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
        }
    }
}


- (NSString *)getAllCache{
    // 获取Caches目录路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    long long folderSize = [self folderSizeAtPath:cachesDir] ;
    CGFloat imgSize =  [[SDImageCache sharedImageCache] getSize];
    CDebugLog(@"imgSize %f", imgSize);
    NSString *foderSize = [NSString stringWithFormat:@"%.2fMB", (double)folderSize / (1024 * 1024)];
    return foderSize;
}


- (void)deleteAllCache{
    dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [[SDImageCache sharedImageCache] cleanDisk];
    });
    dispatch_async(dispatch_get_main_queue(), ^{
        [self deleteWebCache];
    });
}

- (NSString *)dataCachePath:(NSString *)name{
    NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *path = [cacheFolder stringByAppendingPathComponent:name];
    return path;
}

#pragma mark -  remove

#define APP_CACHE_DATABASE_NAME  @"CedarAppCache"

//key 目前是orderID
- (void)addWillRemoveCacheImageArray:(NSArray *)array key:(NSString *)key{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([array count]>0 && !IsEmptyStr(key)) {
            BOOL isSave = YES;
            YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CACHE_DATABASE_NAME];
            NSArray *orderIDArray  = (NSArray *)[diskCache objectForKey:@"CacheProductAgreementOrderID"];
            NSMutableArray *newArray =  [NSMutableArray array];
            if ([orderIDArray count]>0) {
                for (NSString *orderID in orderIDArray) {//检测是否新的订单ID
                    if ([key isEqualToString:orderID]) {
                        #if DEBUG
                        CLog(@"cache key has exist %@",key);
                        #endif
                        isSave = NO;
                        break;
                    }
                }
                if (isSave) {
                    [newArray addObjectsFromArray:orderIDArray];
                }
            }
            if (isSave) {
                [newArray addObject:key];
                [diskCache setObject:newArray forKey:@"CacheProductAgreementOrderID"];
                [diskCache setObject:array forKey:key];//保存产品ID对应的数据
#if DEBUG
                CLog(@"cache key add %@",key);
#endif
            }
        }
    });
}

- (void)removeCacheImages{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        YYCache *diskCache =  [[YYCache alloc]initWithName:APP_CACHE_DATABASE_NAME];
        NSArray *array  = (NSArray *)[diskCache objectForKey:@"CacheProductAgreementOrderID"];
        for (NSString *key in array) {
            NSArray *orderIDArray  = (NSArray *)[diskCache objectForKey:key];
            for (NSString *imageKey in orderIDArray) {
                if ([[SDImageCache sharedImageCache] diskImageExistsWithKey:imageKey]) {
                    [[SDImageCache sharedImageCache]removeImageForKey:imageKey];
#if DEBUG
                    CLog(@"cache key removed: %@",key);
#endif
                }
            }
        }
        [diskCache removeAllObjects];
    });
}

//Libiray/Cache/ShareFile
+ (NSString *)writeShareLocalCacheData:(NSData *)data{
    // 设置存储路径
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
                            stringByAppendingPathComponent:@"ShareFile"];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:cachesPath isDirectory:&isDir];
    if(!(existed && isDir)) {
        BOOL result = [fileManager createDirectoryAtPath:cachesPath withIntermediateDirectories:YES attributes:nil error:nil];
        CLog(@"ShareFile create: %d",result);
    }
    
    cachesPath = [cachesPath stringByAppendingPathComponent:@"shareImage.png"];
    
    // 判读缓存数据是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        // 删除旧的缓存数据
        [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
    }
    
    // 存储新的缓存数据
    [data writeToFile:cachesPath atomically:YES];
    return cachesPath;
}

+ (void)removeShareLocalCacheData{
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]
                            stringByAppendingPathComponent:@"ShareFile"];
    cachesPath = [cachesPath stringByAppendingPathComponent:@"shareImage.png"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        // 删除旧的缓存数据
        BOOL result = [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
        CLog(@"shareImage.png delete: %d",result);
    }
}


@end
